<?php

namespace frontend\controllers;

use yii\web\Controller;
use frontend\models\UserForm;
use frontend\models\TbaMemberinfo;

class UserController extends Controller {
	
	public function actionIndex(){
		if(\Yii::$app->user->isGuest){
			
			$this->redirect(['user/login']);
		}
		
		return $this->render('index');
	}
	
	public function actionRegister(){
		$model=new UserForm();
		$model->scenario='register';//赋予场景
		//判断是否有提交动作
		if(\Yii::$app->request->isPost){
			$model->attributes=\Yii::$app->request->post('UserForm');//块赋值
			//进行表单验证
			if($model->validate()){
				//进行数据写入
				$user=new TbaMemberinfo();
				$user->username=$model->username;
				$user->auth_key=\Yii::$app->security->generateRandomString();
				$user->Pwd=substr(md5(trim($model->Pwd.$user->auth_key)), 9,12);//密码通过md5加密后去第九位后边的12个字符
				$user->Email=$model->Email;
				$user->lName=$model->lName;
				$user->Remark=$model->Remark;
				if($user->save()){
					//进行权限控制，跳转登陆页面
					
					
					$this->redirect(['user/login']);
				}else{
					
					throw new \Exception('数据写入失败', '404');
				}
				
			}
		}
		return $this->render('register',['model'=>$model]);
	}
	
	public function actions(){
		return [
			'captcha'=>[
				'class'=>'yii\captcha\CaptchaAction',
				'maxLength'=>4,
				'minLength'=>4
			],
		];
	}
	
	public function actionLogin(){
		$loginModel=new UserForm();
		$loginModel->scenario='login';
		
		 if(\Yii::$app->request->isPost){
			$loginModel->attributes=\Yii::$app->request->post('UserForm');
			
			 if($loginModel->validate() && $loginModel->login()){
			 	\Yii::$app->session->set('userid',\Yii::$app->user->getId());
			  	\Yii::$app->session->set('username',$loginModel->username);
			  	
				$this->redirect(['index']);
			} 
		} 
		return $this->render('login',['loginModel'=>$loginModel]);
	}
	
	public function actionLogout(){
		\Yii::$app->user->logout();
		$this->redirect(['user/login']);
	}
	
}

?>